package cn.diancan.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import cn.diancan.dao.MyBaseDao;
import cn.diancan.dto.ScoreRecordDto;
import cn.diancan.exception.OutMsgException;
import cn.diancan.model.PurchaseSaleOrder;
import cn.diancan.model.ScoreRecord;
import cn.diancan.model.ShopCustomer;
import cn.diancan.model.types.CommonType;
import cn.diancan.model.types.PurchaseSaleOrderType;
import cn.diancan.model.types.ScoreRecordStatusType;
import cn.diancan.model.types.ScoreRecordType;
import cn.diancan.model.types.ScoreRecordUseType;
import cn.diancan.service.ScoreRecordService;
import cn.diancan.util.ObjectUtils;
import cn.diancan.vo.other.Pager;
import cn.diancan.vo.other.ResultVoUtil;

@Component("scoreRecordService")
public class ScoreRecordServiceImpl implements ScoreRecordService {

    @Resource(name = "MyBaseDao")
    private MyBaseDao<ScoreRecord> scoreRecordDao;
    @Resource(name = "MyBaseDao")
    private MyBaseDao<ShopCustomer> shopCustomerDao; 
    @Resource(name="MyBaseDao")
    private MyBaseDao<PurchaseSaleOrder> purchaseOrderDao;
    
    
 

    @Override
    public boolean saveScoreRecord(Long shopCustomerId,String purchaseSaleOutOrderNumber,Double outRealTotalPrice,String recordReMarks,String ip)throws OutMsgException, Exception {
	ScoreRecord scoreRecord =scoreRecordDao.get("FROM ScoreRecord WHERE purchaseSaleOutOrderNumber=? AND isDelete=? ", 
		new Object[]{purchaseSaleOutOrderNumber,CommonType.Delete.NO});
	if(null!=scoreRecord){
	      throw  new OutMsgException("参数错误");
	}
	scoreRecord= new ScoreRecord(); 
	scoreRecord.init(); 
	scoreRecord.setPurchaseSaleOrderId(null);
	scoreRecord.setIp(ip);
	scoreRecord.setShopCustomerId(shopCustomerId);
	scoreRecord.setPurchaseSaleOutOrderNumber(purchaseSaleOutOrderNumber);
	
	
	
	scoreRecord.setRecordStatus(ScoreRecordStatusType.NOHANDLE.getType());
	scoreRecord.setRecordType(ScoreRecordType.ORDER.getType());
	scoreRecord.setUseWay("未知");
	scoreRecord.setUseType(ScoreRecordUseType.UNKNOW);
	scoreRecord.setIsDelete(CommonType.Delete.NO);
	 int score =0;
	if(null!=outRealTotalPrice){
	       score=outRealTotalPrice.intValue(); 
		if(score<0){
		    score = 0-score;
		    scoreRecord.setUseType(ScoreRecordUseType.SUBSCORE);
		}else if(score>0){ 
		    scoreRecord.setUseType(ScoreRecordUseType.ADDSCORE);
		} 
		scoreRecord.setScoreValue(score);
		scoreRecord.setUseWay("结算单");
	    scoreRecord.setRecordReMarks(recordReMarks+"$(金额:"+outRealTotalPrice+")");
	    scoreRecord.setOutRealTotalPrice(outRealTotalPrice);
	    scoreRecord.setRecordStatus(ScoreRecordStatusType.SUCCESS.getType());
	}else{
	    scoreRecord.setRecordReMarks(recordReMarks);
	} 
	
	scoreRecordDao.save(scoreRecord);
	if(null!=outRealTotalPrice){
	   return updateShopCustomer(shopCustomerId, scoreRecord.getUseType(), score,null); 
	}
	
	

	//V1
	/*
	PurchaseSaleOrder order = purchaseOrderDao.get("FROM PurchaseSaleOrder WHERE outOrderNumber=? ", new Object[]{purchaseSaleOutOrderNumber}); 
	ScoreRecord scoreRecord =scoreRecordDao.get("FROM ScoreRecord WHERE purchaseSaleOutOrderNumber=? AND isDelete=? ", 
		new Object[]{purchaseSaleOutOrderNumber,CommonType.Delete.NO});
	if(null!=scoreRecord){
	      throw  new OutMsgException("参数错误");
	}
	scoreRecord= new ScoreRecord();
	
	scoreRecord.init(); 
	scoreRecord.setPurchaseSaleOrderId(null);
	scoreRecord.setIp(ip);
	scoreRecord.setShopCustomerId(shopCustomerId);
	scoreRecord.setPurchaseSaleOutOrderNumber(purchaseSaleOutOrderNumber);
	scoreRecord.setRecordReMarks(recordReMarks);
	scoreRecord.setRecordStatus(ScoreRecordStatusType.NOHANDLE.getType());
	scoreRecord.setUseWay("未知");
	scoreRecord.setUseType(ScoreRecordUseType.UNKNOW);
	scoreRecord.setIsDelete(CommonType.Delete.YES);
	Double consumeMoney =null;
	if(null!=order){ 
	    PurchaseSaleOrderType type = PurchaseSaleOrderType.find(order.getPurchaseSaleOrderType()); 
	    scoreRecord.setPurchaseSaleOrderId(order.getId());
	    scoreRecord.setUseWay(type.getTypeName()+"单");  
	    scoreRecord.setRecordStatus(ScoreRecordStatusType.SUCCESS.getType()); 
	    consumeMoney = order.getTotalPrice();
	}
	
	scoreRecordDao.save(scoreRecord);
	if(null!=order){
	    updateShopCustomer(shopCustomerId, scoreRecord.getUseType(), scoreRecord.getScoreValue(),consumeMoney);
	}
	*/
  
	return true;
    }
    
    

    @Override
    public boolean saveScoreRecord(Long shopCustomerId, Integer recordType,
	    String useWay, String recordReMarks, Integer useType,Integer scoreValue, String ip,
	    Integer recordStatus) throws OutMsgException, Exception{
	
	ScoreRecord scoreRecord = new ScoreRecord();
	scoreRecord.init();
	scoreRecord.setShopCustomerId(shopCustomerId);
	scoreRecord.setRecordReMarks(recordReMarks);
	scoreRecord.setRecordType(recordType);
	scoreRecord.setUseType(useType);
	scoreRecord.setScoreValue(scoreValue);
	scoreRecord.setUseWay(useWay);
	scoreRecord.setIp(ip);
	scoreRecord.setRecordStatus(recordStatus);
	
	 
	scoreRecordDao.save(scoreRecord); 
	updateShopCustomer(shopCustomerId, useType, scoreValue,null);
	return true;
    }
    
    
    
    
    @Override
    public boolean updateHandleScoreRecord(String purchaseSaleOutOrderNumber)   throws OutMsgException, Exception {
	PurchaseSaleOrder order = purchaseOrderDao.get("FROM PurchaseSaleOrder WHERE outOrderNumber=? ", new Object[]{purchaseSaleOutOrderNumber});
	if(null==order){ 
	    throw new OutMsgException("参数错误");
	}
	ScoreRecord scoreRecord =scoreRecordDao.get("FROM ScoreRecord WHERE purchaseSaleOutOrderNumber=? AND isDelete=? ", 
		new Object[]{purchaseSaleOutOrderNumber,CommonType.Delete.NO});
	if(null==scoreRecord){
	    //不成功.
	    throw new OutMsgException("参数错误");
	}
	PurchaseSaleOrderType type = PurchaseSaleOrderType.find(order.getPurchaseSaleOrderType()); 
	
	int score=order.getOutRealTotalPrice().intValue();
	
	if(score<0){
	    score = 0-score;
	    scoreRecord.setUseType(ScoreRecordUseType.SUBSCORE);
	}else if(score>0){ 
	    scoreRecord.setUseType(ScoreRecordUseType.ADDSCORE);
	}
	scoreRecord.setPurchaseSaleOrderNumber(order.getOrderNumber());
	scoreRecord.setScoreValue(score); 
	scoreRecord.setPurchaseSaleOrderId(order.getId());
	scoreRecord.setUseWay(type.getTypeName()+"单");  
	scoreRecord.setRecordStatus(ScoreRecordStatusType.SUCCESS.getType()); 
	Double consumeMoney = 0d;
	consumeMoney = order.getTotalPrice();
	scoreRecordDao.save(scoreRecord);
	
	if(score!=0){
	    return updateShopCustomer(scoreRecord.getShopCustomerId(), scoreRecord.getUseType(), scoreRecord.getScoreValue(),consumeMoney);
	}else{
	    return true;
	}
	
	
    }


    
 


    private boolean updateShopCustomer(Long shopCustomerId,Integer useType,Integer scoreValue ,Double consumeMoney)throws OutMsgException, Exception{
	if(null==shopCustomerId){
	    throw new OutMsgException("参数错误");
	}
	ShopCustomer shopCustomer=shopCustomerDao.get("FROM ShopCustomer WHERE id=? AND isDelete=?", new Object[]{shopCustomerId,CommonType.Delete.NO});
	if(null==shopCustomer){
	    throw new OutMsgException("参数错误");
	}
	if(null==useType ||  (!useType.equals(ScoreRecordUseType.ADDSCORE) && !useType.equals(ScoreRecordUseType.SUBSCORE))){
	    throw new OutMsgException("参数错误 :积分操作");
	}
	if(null==scoreValue || scoreValue<=0){
	    throw new OutMsgException("参数错误 :积分值");
	}
	Integer surplusScore =shopCustomer.getSurplusScore();
	surplusScore = null==surplusScore?0:surplusScore;
	Integer totalScore = shopCustomer.getTotalScore();
	totalScore = null==totalScore?0:totalScore;
	
	if(useType.equals(ScoreRecordUseType.ADDSCORE)){
	    shopCustomer.setSurplusScore(surplusScore+scoreValue);
	    shopCustomer.setTotalScore(totalScore+scoreValue); 
	}
	if(useType.equals(ScoreRecordUseType.SUBSCORE)){
	    shopCustomer.setSurplusScore(surplusScore-scoreValue);
	    shopCustomer.setTotalScore(totalScore-scoreValue); 
	}
	if(null!=consumeMoney){
	    Double totalConsumeMoney =shopCustomer.getTotalConsumeMoney();
	    totalConsumeMoney = totalConsumeMoney==null?0d:totalConsumeMoney;
	    shopCustomer.setTotalConsumeMoney(totalConsumeMoney+consumeMoney);
	}
	shopCustomerDao.update(shopCustomer);
	
	return true;
    }



    @Override
    public boolean saveScoreRecord(ScoreRecord scoreRecord)   throws OutMsgException, Exception {
	if (null == scoreRecord) {
	    throw new OutMsgException("参数错误");
	}
	scoreRecordDao.save(scoreRecord);
	return true;
    }

    @Override
    public boolean deleteScoreRecordById(Long scoreRecordId)    throws OutMsgException, Exception {
	if (null == scoreRecordId || scoreRecordId <= 0l) {
	    throw new OutMsgException("参数错误");
	}
	ScoreRecord scoreRecord = findbyScoreRecordId(scoreRecordId);
	if (null == scoreRecord) {
	    throw new OutMsgException("参数错误");
	}
	scoreRecordDao.update(scoreRecord);
	return true;
    }

    @Override
    public boolean updateScoreRecord(ScoreRecord scoreRecord)    throws OutMsgException, Exception {
	if (null == scoreRecord) {
	    throw new OutMsgException("参数错误");
	}
	scoreRecordDao.update(scoreRecord);
	return true;
    }

    @Override
    public ScoreRecord findbyScoreRecordId(Long scoreRecordId)    throws OutMsgException, Exception {
	if (null == scoreRecordId || scoreRecordId <= 0l) {
	    throw new OutMsgException("参数错误");
	}
	return scoreRecordDao.get("FROM ScoreRecord WHERE id=? AND isDelete=?",
		new Object[] { scoreRecordId, 0 });
    }

    @Override
    public Pager findScoreRecordPager(Pager pager)    throws OutMsgException, Exception {
	Integer pageNo = pager.getPageNumber();
	Integer row = pager.getPageSize();
	List<Object> param = new ArrayList<Object>();

	String hql = "FROM ScoreRecord WHERE isDelete=? ";
	List<ScoreRecord> scoreRecords = scoreRecordDao.find(hql, new Object[] { 0 },	pageNo, row);
	pager.setList(scoreRecords);

	Long count = scoreRecordDao.count("SELECT COUNT(id) " + hql, param);
	pager.setTotalCount(count.intValue());
	return pager;
    }
    
    

      @Override
    public Pager findScoreRecordPager(Pager pager,String customerName,String customerPhoneNum ,String purchaseSaleOutOrderNumber) throws OutMsgException, Exception {
	  	
		Integer pageNo = pager.getPageNumber();
		Integer row = pager.getPageSize();
		List<Object> param = new ArrayList<Object>();

		String pex_hql = "SELECT s1.id AS scoreRecordId,s1.shopCustomerId,s1.recordType,s1.useWay,s1.recordReMarks,s1.useType,s1.scoreValue,s1.recordStatus"+
			",s1.purchaseSaleOrderId,s1.purchaseSaleOutOrderNumber,s1.purchaseSaleOrderNumber,s1.ip,s2.customerName,s2.customerPhoneNum ";
		String hql=" FROM ScoreRecord AS s1 LEFT JOIN ShopCustomer AS s2 ON s1.shopCustomerId=s2.id WHERE s1.isDelete=? AND s2.isDelete=? ";
		
		param.add(CommonType.Delete.NO); 
		param.add(CommonType.Delete.NO); 
		
		if(ObjectUtils.isNotBlank(customerName)){
		    hql+=" AND  instr(s2.customerName,?)>0 ";
		    param.add(customerName); 
		}
		
		if(ObjectUtils.isNotBlank(customerPhoneNum)){
		    hql+=" AND  instr(s2.customerPhoneNum,?)>0 ";
		    param.add(customerPhoneNum); 
		}
		if(ObjectUtils.isNotBlank(purchaseSaleOutOrderNumber)){
		    hql+=" AND  instr(s1.purchaseSaleOutOrderNumber,?)>0 ";
		    param.add(purchaseSaleOutOrderNumber); 
		}
		
		hql+=" Order by s1.id DESC ";
		
		List<Object[]> lsObj = scoreRecordDao.findSql(pex_hql+ hql, param, pageNo, row);
		List<ScoreRecordDto> scoreRecords=  ResultVoUtil.object2Model(ScoreRecordDto.class, lsObj, pex_hql+ hql);
		
		pager.setList(scoreRecords); 

		Object count = scoreRecordDao.countSQL("SELECT COUNT(s1.id) " + hql, param.toArray());
		pager.setTotalCount(null==count?0:Integer.valueOf(count.toString()));
		return pager;
    }



    @Override
    public List<ScoreRecord> findScoreRecordList(Integer recordType , Integer recordStatus ,Integer pageNo,Integer row)        throws OutMsgException, Exception {
	String hql = "FROM ScoreRecord WHERE isDelete=? ";
	List<Object> param = new ArrayList<Object>();
	param.add(0);
	if(ScoreRecordType.checkExists(recordType)){
	    hql+=" AND recordType=? ";
	    param.add(recordType);
	}
	if(ScoreRecordStatusType.checkExists(recordStatus)){
	    hql+=" AND recordStatus=? ";
	    param.add(recordStatus);
	}
	
	return scoreRecordDao.find(hql , param, pageNo, row);
    }


 

      
      
}